package cn.evun.tms.generator.task;

import cn.evun.tms.generator.Constants;
import cn.evun.tms.generator.config.Configuration;
import cn.evun.tms.generator.framework.AbstractApplicationTask;
import cn.evun.tms.generator.framework.context.ApplicationContext;
import cn.evun.tms.generator.handler.BaseHandler;
import cn.evun.tms.generator.handler.impl.ServiceImplHandler;
import cn.evun.tms.generator.model.DtoInfo;
import cn.evun.tms.generator.model.EntityInfo;
import cn.evun.tms.generator.model.ServiceImplInfo;
import cn.evun.tms.generator.model.ServiceInfo;

import java.util.ArrayList;
import java.util.List;

public class ServiceImplTask extends AbstractApplicationTask {

	private static String SERVICEIMPL_FTL = "template/ServiceImpl.ftl";

	@SuppressWarnings("unchecked")
	@Override
	protected boolean doInternal(ApplicationContext context) throws Exception {
		logger.info("开始生成serviceImpl...");
		List<ServiceImplInfo> list = (List<ServiceImplInfo>) context.getAttribute("serviceImplInfos");

		BaseHandler<ServiceImplInfo> baseHandler = null;
		for (ServiceImplInfo info : list) {
			baseHandler = new ServiceImplHandler(SERVICEIMPL_FTL, info);
			baseHandler.execute(context);
		}

		logger.info("结束生成serviceImpl。。。");
		return false;
	}

	@Override
	protected boolean doBefore(ApplicationContext context) throws Exception {
		super.doAfter(context);

		List<ServiceInfo> serviceInfos = (List<ServiceInfo>) context.getAttribute("serviceInfos");
		List<EntityInfo> entityInfos = (List<EntityInfo>) context.getAttribute("entityInfos");
		List<DtoInfo> dtoInfos = (List<DtoInfo>) context.getAttribute("dtoList");

		List<ServiceImplInfo> serviceImplInfos = new ArrayList<ServiceImplInfo>();
		ServiceImplInfo serviceImplInfo = null;
		for (int i = 0; i < serviceInfos.size(); i++) {
			ServiceInfo serviceInfo = serviceInfos.get(i);
			EntityInfo entityInfo = entityInfos.get(i);
			DtoInfo dtoInfo = dtoInfos.get(i);
			serviceImplInfo = new ServiceImplInfo();
			serviceImplInfo.setEntityDesc(entityInfo.getEntityDesc());
			serviceImplInfo.setEntityName(entityInfo.getEntityName());
			serviceImplInfo.setLowerEntityName(entityInfo.getEntityName().substring(0, 1).toLowerCase() + entityInfo.getEntityName().substring(1));
			serviceImplInfo.setPackageStr(Configuration.getString("serviceImpl.package"));
			serviceImplInfo.setServiceType(serviceInfo.getPackageStr() + Constants.CHARACTER_POINT + serviceInfo.getClassName());
			serviceImplInfo.setDtoInfo(dtoInfo);
			serviceImplInfo.setClassName(entityInfo.getClassName() + "ServiceImpl");
			serviceImplInfos.add(serviceImplInfo);
		}
		context.setAttribute("serviceImplInfos", serviceImplInfos);

		return true;
	}
}
